package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.PermissionDao;
import com.itheima.entity.PageResult;
import com.itheima.pojo.Permission;
import com.itheima.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service(interfaceClass = PermissionService.class)
@Transactional
public class PermissionServiceImpl implements PermissionService {

    @Autowired
    private PermissionDao permissionDao;

    /**
     * 分页查询
     * @param currentPage
     * @param pageSize
     * @param queryString
     * @return
     */
    @Override
    public PageResult pageQuery(Integer currentPage, Integer pageSize, String queryString) {
        //去除前后空格
        if (queryString != null && queryString.length() > 0){
            queryString = queryString.trim();
        }

        PageHelper.startPage(currentPage,pageSize);
        Page<Permission> page = permissionDao.selectByCondition(queryString);
        List<Permission> result = page.getResult();
        long total = page.getTotal();

        return new PageResult(total,result);
    }

    /**
     * 新建
     * @param permission
     */
    @Override
    public void add(Permission permission) {
        permissionDao.add(permission);
    }

    /**
     * 删除
     * @param id
     */
    @Override
    public void delete(Integer id) {
        //注意：不能直接删除，需要判断当前[权限]是否和[角色]关联，如果已经和[角色]进行了关联则不允许删除
        long count = permissionDao.findCountByCheckItemId(id);
        if (count > 0){
            //存在引用,不能直接删除
            throw new RuntimeException("当前权限被引用,不能直接删除");
        }else {
            permissionDao.deleteById(id);
        }
    }

    /**
     * 通过id查询
     * @param id
     * @return
     */
    @Override
    public Permission findById(Integer id) {
        return permissionDao.findById(id);
    }

    /**
     * 编辑
     * @param permission
     */
    @Override
    public void edit(Permission permission) {
        permissionDao.edit(permission);
    }
}
